//
//  Utility.m
//  BaseTdkc
//
//  Created by DavidHuang on 16/7/2.
//  Copyright © 2016年 黄栋炜. All rights reserved.
//

#import "Utility.h"
#import "AFNetworkReachabilityManager.h"

@implementation Utility
+ (UIWindow *)mainWindow {
    UIApplication *app = [UIApplication sharedApplication];
    if ([app.delegate respondsToSelector:@selector(window)]) {
        return [app.delegate window];
    } else {
        return [app keyWindow];
    }
}
+ (BOOL)isEmpty:(NSString *)content {
    return !content || [self trim:content].length == 0;
}
+ (NSString *)trim:(NSString *)content {
    if (![content isKindOfClass:[NSString class]]) {
        return @"";
    } else {
        return [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }
}
+ (void)cornerRadiusToClip:(UIView *)view radius:(float)radius {
    view.layer.cornerRadius = radius;
    view.clipsToBounds = YES;
}
+ (CGSize)getTextString:(NSString *)text textFont:(UIFont *)textFont frameWidth:(float)width {
    CGSize constraint = CGSizeMake(width, MAXFLOAT);
    if (text) {
        NSAttributedString *attributedText = [[NSAttributedString alloc]initWithString:text attributes:@{NSFontAttributeName:textFont}];
        CGRect rect = [attributedText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin context:nil];
        CGSize size = rect.size;
        return size;
    } else {
        return CGSizeZero;
    }
}
+ (NSString *)trimWithNull:(id)text {
    NSString *textString = nil;
    if([text isKindOfClass:[NSString class]] || [text isKindOfClass:[NSNumber class]]){
        textString = [NSString stringWithFormat:@"%@",text];
        if ([self isEmpty:textString]) {
            return @"";
        }
    }else{
        return @"";
    }
    return textString;
}
+ (BOOL)isCNPhoneNumber:(NSString *)CNPhoneNumber {
    NSString *pattern = @"[0-9]{11}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [pred evaluateWithObject:CNPhoneNumber];
}
+ (BOOL)isPassword:(NSString *)password {
    NSString *pattern = @"[^\\s]{6,16}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [pred evaluateWithObject:password] && ![Utility isContainsEmoji:password] &&![Utility isChinese:password];
}
+ (BOOL)isContainsEmoji:(NSString *)string {
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    return isEomji;
    
}
+ (BOOL)isChinese:(NSString *)chinese {
    NSString *pattern = @".*[\\u4e00-\\u9faf].*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [pred evaluateWithObject:chinese];
}
+ (BOOL)isCodeNumber:(NSString *)codeNumber {
    NSString *pattern = @"[0-9]{6}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [pred evaluateWithObject:codeNumber];
}

+ (BOOL)isNumber:(NSString *)NumberStr {
    NSString *pattern = @"^[0-9]{1,}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [pred evaluateWithObject:NumberStr];
}

//邮箱验证
+ (BOOL) justEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
+ (NSString *)timeStringWithDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    formatter.timeZone = [NSTimeZone systemTimeZone];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *datestr = [formatter stringFromDate:date];
    return datestr;
}
+ (NSString *)timeToMinuteStringWithDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    formatter.timeZone = [NSTimeZone systemTimeZone];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *datestr = [formatter stringFromDate:date];
    return datestr;
}
+ (NSData *)compressImage:(UIImage *)compImage imageLength:(NSInteger)imageLength {
    NSData *imageData = UIImageJPEGRepresentation(compImage, 1.0);
    float options = 1.0;
    while (imageData.length / 1024 > imageLength) {
        options -= 0.1;
        if (options <= 0) {
            break;
        }
        imageData = UIImageJPEGRepresentation(compImage, options);
    }
    return imageData;
}
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    if (img.size.width / size.width > 1.0 || img.size.height / size.height > 1.0) {
        if (img.size.width / size.width > img.size.height / size.height) {
            if (img.size.width>size.width){
                size.width = size.width;
                size.height = img.size.height * size.width /img.size.width;
            } else {
                return img;
            }
        } else {
            if (img.size.height>size.height){
                size.width = img.size.width * size.height /img.size.height;
                size.height = size.height;
            } else {
                return img;
            }
        }
    }
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
+ (NSString *)documentPathWithSubDocumentName:(NSString *)subDocumentName {
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(
                                                               NSDocumentDirectory,
                                                               NSUserDomainMask,
                                                               YES);
    NSString *documentFolderPath = [searchPaths objectAtIndex:0];

    //往应用程序路径中添加数据库文件名称
    NSString *filePath;
    filePath = [documentFolderPath stringByAppendingPathComponent:subDocumentName];
    return filePath;
}


+ (BOOL)getNetStatus {
    return [AFNetworkReachabilityManager sharedManager].isReachable;
}


@end
